<?php

namespace Home\Controller;

class VoteController extends HomeController
{

    /**
     * 投票活动控制器.
     *
     * @param $id
     */
    public function activity($id = null) {

        if (!((int)$id > 0)) {
            echo '无活动id';exit;
        }

        // 分类
        $category_name = 'vote';
        // 获取分类信息
        $category = $this['Category']->info(['name'=>$category_name]);
        $category_item = $this['Category']->info(['id'=>12]);

        // 获取活动分类的模型信息
        $model = $this['Model']->info(['id'=>$category['model_id']]);
        // 获取选项分类的模型信息
        $model_item = $this['Model']->info(['id'=>$category_item['model_id']]);

        // 活动增加浏览人数
        $this[$model['name']]->where(['id' => $id])->setInc('view');
        // 获取活动
        $vote = $this[$model['name']]->info(['id' => $id]);

        // 关注限制
        $uid = 0;
        if ($vote['control'] == 1) {
            // 所有人可以投票
            // 需要微信登录
            trace('所有人可以投票','vote');
            if ( !($uid = check_login($this)) ){
                //$this->display('Public/need_wechat');
                //exit;
                $this->assign('uid', 0);
                $this->assign('is_login','false');
                trace('未登录', 'vote');
            } else {
                trace('已登录', 'vote');
                $this->assign('is_login','true');
                $this->assign('uid', $uid);
            }
        } else {
            // 关注的人可以投票
            trace('关注的人可以投票','vote');
            if( !session('user.uid') ) {
                trace('未登录', 'vote');
                $this->assign('uid', 0);
                $this->assign('is_login','false');
            } else {
                trace('已登录', 'vote');
                $uid = session('user.uid');
                $this->assign('is_login','true');
                $this->assign('uid', $uid);
            }
        }




        // 获取选项
//        $items = $this[$model_item['name']]->get(['pid' => $id]);
        $items = M()->table([C('DB_PREFIX').$model_item['name']=>'item', C('DB_PREFIX').'picture'=>'p'])->field('item.*,p.path')->where('item.cover_id=p.id and item.pid="'.$id.'"')->order('item.sort ASC')->select();

        // 使用远程图片
        foreach($items as $k=>$v) {
            if (isset($v['cover_url']) && $v['cover_url']) {
                $items[$k]['path'] = $v['cover_url'];
            }
        }

        // 获取参数人数
        $vote['item_number'] = count($items);
        // 投票人次
        $vote['vote_number'] = array_sum(array_map(function($v){
            return $v['vote'];
        }, $items));

		// 投票记录
        if ($uid > 0) {
            if ($records = $this['ActivityRecord']->where(['uid' => $uid, 'activity_id' => $vote['id']])->getField('id,id,item_id,created_at')) {
                $vote['have_voted'] = 'true';
            } else {
                $vote['have_voted'] = 'false';
            }
        } else {
            $records = '';
        }
        $this->assign('records_json', json_encode($records));

        $this->assign('category',$category);
        $this->assign('category_item',$category_item);
        $this->assign('vote', $vote);
        $this->assign('vote_json', json_encode($vote));
        $this->assign('items', $items);
        $this->assign('items_json', json_encode($items));
        $this->assign('refresh_time', C('REFRESH_TIME'));
        $this->assign('refresh_prob', C('REFRESH_PROB'));

        $this->display('activity2');
    }

    public function clear(){
        session(null);
    }


    /**
     * 1.获取投票活动数据，2.获取投票选项数据，3.进行投票
     *
     */
    public function api(){
        $action = $_REQUEST['action'];
        switch($action){
            case 'getVotes':
                $res['error'] = 0;
                $ids_arr = $_POST['votes'];
                // TODO:获取投票活动数据
                $list = D('ActivityVote')->get($ids_arr);
                // 处理时间与进度
                foreach($list as &$v) {
                    if ((time() - $v['start']) >= 0 && (time() - $v['end']) <= 0) {
                        // 开始中
                        $days = floor(($v['end'] - time())/(24*3600));
                        $hours = floor(($v['end'] - time())%(24*3600)/3600);
                        $minutes = floor(($v['end'] - time())%3600/60);
                        $seconds = floor(($v['end'] - time())%60);
                        $str = '距离结束 ';
                        if ($days > 0) {
                            $str .= $days . '天';
                        }
                        if ($hours > 0) {
                            $str .= $hours . '小时';
                        }
                        if ($minutes > 0) {
                            $str .= $minutes . '分钟';
                        }
                        $str .= $seconds . '秒';

                        $v['time'] = $str;
                        $v['progress'] = ceil((time() - $v['start'])/($v['end'] - $v['start'])*100);

                    } else if ((time() - $v['start']) < 0) {
                        // 开始前
                        $days = floor(($v['start'] - time())/(24*3600));
                        $hours = floor(($v['start'] - time())%(24*3600)/3600);
                        $minutes = floor(($v['start'] - time())%3600/60);
                        $seconds = floor(($v['end'] - time())%60);

                        $str = '距离开始 ';

                        if ($days > 0) {
                            $str .= $days . '天';
                        }
                        if ($hours > 0) {
                            $str .= $hours . '小时';
                        }
                        if ($minutes > 0) {
                            $str .= $minutes . '分钟';
                        }

                        $str .= $seconds . '秒';

                        $v['time'] = $str;
                        $v['progress'] = 0;

                    } else if ((time() - $v['end']) > 0) {
                        // 结束后
                        $v['time'] = '已结束';
                        $v['progress'] = 100;
                        $v['background-color'] = '#d6d6d6';
                    }
                }
                $res['data'] = $list;

                break;
            case 'vote':
                /**
                 * 错误码： 0:无错误  1:参数错误 2:参数错误(找不到内容) 3:活动已结束 4:参数错误(用户被禁止) 5:已经投过票
                 */
                // 返回数据格式
                $res = ['error'=>0, 'msg'=>''];

                // 获取参数
                $vote_id = I('vote_id',0);
                $vote_item_id = I('item_id',0);
                $uid = I('uid',0);

                // 检查参数
                if (!($vote_id > 0 && $vote_item_id > 0 && $uid)) {
                    $res['error'] = 1;
                    $res['msg'] = '参数错误';
                    goto res;// 直接返回
                }

                // 检查用户
                if (!(($user = get_user($uid)) && $user['status'] == 1)) {
                    $res['error'] = 2;
                    $res['msg'] = '用户状态不正确';
                    $res['user'] = $user;
                    goto res;// 直接返回
                }

                // 检查ip
                if (!filter_ip(get_client_ip())) {
                    $res['error'] = 3;
                    $res['msg'] = '参数错误';// 屏蔽IP
                    goto res;// 直接返回
                }

                // 是否存在活动与选项
                if (!(($vote = $this['ActivityVote']->info(['id' => $vote_id])) &&
                    ($item = $this[$vote['vote_type']]->info(['id' => $vote_item_id])))) {
                    $res['error'] = 4;
                    $res['msg'] = '参数错误';
                    goto res;// 直接返回
                }

                // 检查活动状态
                if ($vote['start'] > time()) {
                    $res['error'] = 5;
                    $res['msg'] = '活动未开始';
                    goto res;// 直接返回
                }
                if ($vote['end'] < time()) {
                    $res['error'] = 6;
                    $res['msg'] = '活动已结束';
                    goto res;// 直接返回
                }

                // 检查是否有记录
                if ($records = $this['ActivityRecord']->where(['uid' => $uid, 'activity_id' => $vote['id']])->getField('id,id,item_id,created_at')) {
                    // 检查规则
                    // 返回该用户参与该活动的全部记录
                    $res['data']['records'] = $records;
                    $res['data']['vote'] = $vote;
                    switch ($vote['type']) {
                        case 1:
                            // 每个选项可投票一次
                            if (array_2_search($records, 'item_id', $vote_item_id)) {
                                $res['error'] = 7.1;
                                $res['msg'] = '该选项已经投过票了';
                                goto res;
                            }
                            break;
                        case 2:
                            // 每天可投票一次
                            $vote_status = true;
                            foreach( $records as $record) {
                                if ($record['created_at'] >= strtotime(date("Y-m-d"))) {
                                    $vote_status = false;
                                }
                            }
                            if (!$vote_status) {
                                $res['error'] = 7.2;
                                $res['msg'] = '今天已经投过票了';
                                goto res;
                            }
                            break;
                        case 3:
                            // 每天可为每个选项投一票
                            foreach( $records as $record) {
                                if ($record['item_id'] == $vote_item_id && $record['created_at'] >= strtotime(date("Y-m-d"))) {
                                    $res['error'] = 7.3;
                                    $res['msg'] = '今天该选项已经投过票了';
                                    goto res;
                                }
                            }
                            break;
                        case 0:
                        default:
                            $res['error'] = 7.4;
                            $res['msg'] = '已经投过票';
                            goto res;// 直接返回
                    }
                }

                // 添加记录 乐观操作
                $data = [
                    'uid' => $uid,
                    'activity_id' => $vote['id'],
                    'item_id' => $item['id']
                ];
                if (!( $data = $this['ActivityRecord']->create($data))) {
                    $res['error'] = 8;
//                    $res['msg'] = '投票失败'; // 无法添加记录
                    $res['msg'] = '投票失败'.$this['ActivityRecord']->getError(); // 无法添加记录
                    trace($this['ActivityRecord']->getError(), 'vote');
                    goto res;// 直接返回
                }
                if (!( $record_id = $this['ActivityRecord']->add($data))) {
                    $res['error'] = 8.5;
                    $res['msg'] = '投票失败'; // 无法添加记录
                    trace($this['ActivityRecord']->getError(), 'vote');
                    goto res;// 直接返回
                }

                // 投票
                if (!$this[$vote['vote_type']]->where(['id'=>$item['id']])->setInc('vote',1)) {
                    $res['error'] = 9;
                    $res['msg'] = '投票失败'; //无法投票
                    // 删除投票记录
                    $this['ActivityRecord']->where(['id' => $record_id])->delete();
                    goto res;// 直接返回
                }

                // TODO:记录用户状态
                // 分析用户行为是否正常

                $res['error'] = 0;
                $res['msg'] = '投票成功';
                $res['data']['vote'] = $this['ActivityVote']->info(['id' => $vote_id]);
                $res['data']['items'] = M()->table([C('DB_PREFIX').'vote_item_premium'=>'item', C('DB_PREFIX').'picture'=>'p'])->field('item.*,p.path')->where('item.cover_id=p.id and item.pid="'.$vote_id.'"')->select();
                $res['data']['records'] = $records;
                if (!empty($res['data']['records'][$record_id])) {
                    trace('投票异常，100054','error_code');
                } else {
                    $res['data']['records'][$record_id] = ['id'=>$record_id, 'item_id'=>$item['id'], 'created_at'=>time()];
                }


                break;
            case "getData":
                $id = I('vote_id',0);
                $uid = I('uid',0);
//                $uid = 7;//I('uid',0);
                if (!($id > 0)) {
                    $res['error'] = 1;
                    $res['msg'] = '活动ID为空';
                    goto res;
                }

                // 活动增加浏览人数
                $this['ActivityVote']->where(['id' => $id])->setInc('view');
                // 获取活动
                if (!($vote = $this['ActivityVote']->info(['id' => $id]))) {
                    $res['error'] = 2;
                    $res['msg'] = '活动不存在';
                    goto res;
                }

                // 获取选项
                if (!($items = M()->table([C('DB_PREFIX').'vote_item_premium'=>'item', C('DB_PREFIX').'picture'=>'p'])->field('item.*,p.path')->where('item.cover_id=p.id and item.pid="'.$id.'"')->order('item.sort ASC')->select())) {
                    $res['error'] = 3;
                    $res['msg'] = '选项不存在';
                    goto res;
                }

                // 使用远程图片
                foreach($items as $k=>$v) {
                    if (isset($v['cover_url']) && $v['cover_url']) {
                        $items[$k]['path'] = $v['cover_url'];
                    }
                }

                $res['data'] = ['vote' => $vote, 'items' => $items];

                break;
            case "getItems":
                $id = I('vote_id',0);
//                $uid = I('uid',0);
                $uid = 7;//I('uid',0);
                if (!($id > 0)) {
                    $res['error'] = 1;
                    $res['msg'] = '活动ID为空';
                    goto res;
                }

                // 活动增加浏览人数
                $this['ActivityVote']->where(['id' => $id])->setInc('view');
                // 获取活动
                if (!($vote = $this['ActivityVote']->info(['id' => $id]))) {
                    $res['error'] = 2;
                    $res['msg'] = '活动不存在';
                    goto res;
                }

                // 获取选项
                if (!($items = M()->table([C('DB_PREFIX').'vote_item_premium'=>'item', C('DB_PREFIX').'picture'=>'p'])->field('item.*,p.path')->where('item.cover_id=p.id and item.pid="'.$id.'"')->select())) {
                    $res['error'] = 3;
                    $res['msg'] = '选项不存在';
                    goto res;
                }

                // 使用远程图片
                foreach($items as $k=>$v) {
                    if (isset($v['cover_url']) && $v['cover_url']) {
                        $items[$k]['path'] = $v['cover_url'];
                    }
                }

                // 获取参数人数
                $vote['item_number'] = count($items);
                // 投票人次
                $vote['vote_number'] = array_sum(array_map(function($v){
                    return $v['vote'];
                }, $items));

                if ($uid > 0) {
                    $records = $this['ActivityRecord']->where(['uid' => $uid, 'activity_id' => $vote['id']])->getField('id,id,created_at');
                } else {
                    $records = null;
                }

                $res['data'] = ['vote' => $vote, 'items' => $items, 'records' => $records];

                break;
            default:
                $res['error'] = 1;
                $res['msg'] = 'error';
                break;
        }

        res:
        trace($res,'vote.api');
        $this->ajaxReturn($res);
    }
}
